package cdu.javaendwork.Controller.AdoptionMore;

import cdu.javaendwork.dao.impl.Adoption_display_DaoImpl;
import cdu.javaendwork.model.sqlModel.Pet;
import cdu.javaendwork.model.sqlModel.Post;
import cdu.javaendwork.model.sqlModel.Request;
import cdu.javaendwork.model.sqlModel.User;
import cdu.javaendwork.model.utilModel.Adoption_display_info;
import cdu.javaendwork.model.utilModel.Adoption_display_infomation;
import cdu.javaendwork.service.Impl.AdoptionMore.PetServiceImpl;
import cdu.javaendwork.service.Impl.AdoptionMore.PostServiceImpl;
import cdu.javaendwork.service.Impl.AdoptionMore.RequestServiceImpl;
import cdu.javaendwork.service.Impl.User.UserServiceImpl;
import cdu.javaendwork.service.Interface.AdoptionMore.RequestService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/establish_adoption_request", "/adoption_request_display", "/handle_adoption_request"})
public class Adoption_processing_Controller extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String servletPath = req.getServletPath();
        // 发起领养请求
        if (servletPath.equals("/establish_adoption_request")) {
            doEstablish_adoption_request(req, resp);
        } else if (servletPath.equals("/adoption_request_display")) { // 个人中心 查看领养请求界面
            doAdoption_request_display(req, resp);
        } else if (servletPath.equals("/handle_adoption_request")) { // 用户处理领养请求。
            doHandle_adoption_request(req, resp);
        }
    }

    /**
     * 个人中心 查看领养请求界面
     *
     * @param req
     * @param resp
     */
    private void doAdoption_request_display(HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset = utf-8");
        // 我发出的领养请求。通过id查找request表中的信息。
        // 需要字段 username ， post title , post status , request date
        // 1. 从session域中获取当前用户的id
        HttpSession session = req.getSession(false);
        //int uid = 1;
        User user = (User) req.getSession().getAttribute("user");
        int uid = user.getId();


        UserServiceImpl userService = new UserServiceImpl();
        User byId = userService.findById(uid);
        String username = byId.getUsername(); // 获取当前用户的姓名
        req.setAttribute("username", username);

        // 2. 根据用户id， 查询关联的发出的领养帖子
        RequestServiceImpl requestService = new RequestServiceImpl();
        List<Request> requestsList = requestService.filterByUserIdLimit(uid, 1, 10);
        req.setAttribute("requestsList", requestsList); // 用户关联的发出的领养请求

        // 3. 根据领养帖子中帖子id字段，查找关联的帖子信息
        List<Post> postList = new ArrayList<>();
        PostServiceImpl postService = new PostServiceImpl();
        for (Request r : requestsList) {
            int postid = r.getPostid();
            Post byid = postService.findByid(postid);
            postList.add(byid);
        }
        req.setAttribute("postList", postList);

        // 我发起的领养请求。通过id查找request表中的信息。
        // 需要字段 宠物姓名 请求人姓名 username 请求人电话 请求时间
        // 1. 从post表中，查询与用户关联的所有请求
        PetServiceImpl petService = new PetServiceImpl();

        List<Pet> petList = new ArrayList<>();
        List<Post> postList1 = postService.filterByUserIdLimit(uid, 1, 10);

        // 2. 查询帖子关联宠物的信息
        for (Post p : postList1) {
            int petid = p.getPetid();
            Pet byId1 = petService.findById(petid);
            petList.add(byId1);
        }
        // 3. 多表查询，查询post表与request表关联的领养信息
        Adoption_display_DaoImpl adoption_display_dao = new Adoption_display_DaoImpl();
        List<Adoption_display_info> adoption_display_infoList = adoption_display_dao.getDisplayInfoByUserid(uid);

        // 4. 根据displayInfoByUserid集合，查找相关联的请求人信息。
        List<User> userList = new ArrayList<>();
        for (Adoption_display_info a : adoption_display_infoList) {
            int userid = a.getUserid();
            User byId1 = userService.findById(userid);
            userList.add(byId1);
        }

        List<Adoption_display_infomation> adoption_display_infomations = new ArrayList<>();

        for (Adoption_display_info a : adoption_display_infoList) {
            Adoption_display_infomation adoption_display_infomation = new Adoption_display_infomation();
            for (Pet p : petList) {
                if (a.getPetid() == p.getId()) {
                    adoption_display_infomation.setPetName(p.getName());
                    adoption_display_infomation.setPostid(a.getId());
                    adoption_display_infomation.setRequestid(a.getRequestid());
                }
            }
            for (User u : userList) {
                if (a.getUserid() == u.getId()) {
                    adoption_display_infomation.setUserName(u.getUsername());
                    adoption_display_infomation.setUserIphoto(u.getPhone());
                }
            }
            adoption_display_infomation.setDate(a.getDate());
            adoption_display_infomations.add(adoption_display_infomation);
        }
        req.setAttribute("info", adoption_display_infomations);

        try {
            req.getRequestDispatcher("adoption_request_display.jsp").forward(req, resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 用户处理他人向自己申请的领养请求
     *
     * @param req
     * @param resp
     */
    private void doHandle_adoption_request(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset = utf-8");
        PrintWriter out = resp.getWriter();
        //    int userid = 1;
        /*设置处理按钮，（接收、拒绝）
         */
        RequestServiceImpl requestService = new RequestServiceImpl();

        // 1. 读取按钮信息。
        int flag = Integer.parseInt(req.getParameter("inlineRadioOptions"));

        // 取出requestid
        String requestid = req.getParameter("requestid");
        // 取出postid
        String postid = req.getParameter("postid");
        // 通过requestid查询 request信息
        Request request = requestService.findById(Integer.parseInt(requestid));
        // 通过
        if (flag == 1) {
            // refuse
            request.setStatus(3);

        } else {
            // accept
            if (request.getStatus() != 2) {
                request.setStatus(2);
                // 将该帖子关联的其他request记录status改为4
                // 通过postid查request表中其他的记录
//            List<Request> requests = requestService.filterByPostidAndUserid(Integer.parseInt(postid), user.getId());
                List<Request> requests = requestService.filterByPostidAndUserid(Integer.parseInt(postid), request.getUserid());
                for (Request r : requests) {
                    if (r.getStatus() != 3) {
                        r.setStatus(4);
                        requestService.update(r.getId(), r.getHost_user_id(), r.getUserid(), r.getPostid(), r.getStatus(), r.getDate());
                    }
                }
            }

        }
        // 保存到数据库 同时需要维护request表的status字段。

        boolean update1 = requestService.update(request.getId(), request.getHost_user_id(), request.getUserid(), request.getPostid(), request.getStatus(), request.getDate());

        if (update1) {
            out.println("<script>alert('提交成功！');window.location.href='adoption_request_display'</script>");
        } else {
            out.print("<script>alert('提交失败！');window.location.href='adoption_request_display'</script>");
        }
    }

    /**
     * 向他人建立一个领养的请求，在领养中心，实现是否领养功能。
     *
     * @param req
     * @param resp
     */
    private void doEstablish_adoption_request(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        /*
        数据字典：
            host_user_id 发出领养帖子的用户id 主人。
            userid 发起领养请求的id
            postid 帖子的id，宠物信息
            status 请求状态。 发起请求，默认为1
            date 时间
         */


        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset = utf-8");
        int pid = Integer.parseInt(req.getParameter("pid"));
        int hostid = Integer.parseInt(req.getParameter("hostid"));
        User user = (User) req.getSession().getAttribute("user");
        RequestService requestService = new RequestServiceImpl();
        PrintWriter out = resp.getWriter();


        List<Request> requests = requestService.filterByPostIdLimit(pid, 1, 100);
        // 判断宠物是否已经被领养了。

        boolean isAdopted = false;

        if(hostid == user.getId()){
            isAdopted = true;
        }

        for (Request r : requests) {
            if(r.getStatus() == 4 || r.getStatus() == 2){
                isAdopted = true;
            }
            if(r.getUserid() == user.getId()){
                isAdopted = true;
            }

        }

        if (isAdopted) {
            out.println("<script>alert('领养请求发送失败！');window.location.href='post_list'</script>");
        } else {
            if (requestService.insert(hostid, user.getId(), pid, 1, new Timestamp(new java.util.Date().getTime()))) {
                out.println("<script>alert('领养请求发送成功！');window.location.href='post_list'</script>");
            } else {
                out.println("<script>alert('领养请求发送失败！');window.location.href='post_list'</script>");
            }
        }
    }
}
